<template>
	<view style="width:100vw;height:100vh;background-color:#333;">
		<fui-loading type="row" v-show="showLoading" :isFixed="true" isMask="true" maskBgColor="rgba(0, 0, 0, 0.6)"
			text="模卡正在生成中,请耐心等待……" rowColor="#FFFFFF" size="18"></fui-loading>
		<uni-drawer ref="showRight" mode="right" :mask-click="true">
			<scroll-view style="height: 100%;" scroll-y="true">
				<view style="height:40rpx;"></view>
				<view class="flexbc switch-box">
					<view class="switch-title">切换黑白背景</view>
					<switch :checked="UserMokaSet.backgroundColor" color="#FFCC33" style="transform:scale(0.7)"
						@change="bgcolorChange" />
				</view>
				<view class="flexbc switch-box">
					<view class="switch-title">生日</view>
					<switch :checked="UserMokaSet.birthShow" color="#FFCC33" style="transform:scale(0.7)"
						@change="birthChange" />
				</view>
				<view class="flexbc switch-box">
					<view class="switch-title">身材信息</view>
					<switch :checked="UserMokaSet.baseShow" color="#FFCC33" style="transform:scale(0.7)"
						@change="baseChange" />
				</view>
			</scroll-view>
		</uni-drawer>

		<view :style="{
				margin:'auto', 
				width: mokaTemplate.MokaWidth*mokaTemplate.MokaTempRate+'rpx',
				height: mokaTemplate.MokaHeight*mokaTemplate.MokaTempRate+'rpx', 
				backgroundColor: mokaTemplate.BackgroundColor, 
				padding: mokaTemplate.MokaPadding*mokaTemplate.MokaTempRate+'rpx', 
				position: 'relative'
			}">

			<!-- start：二维码 -->
			<!-- <view 
				:style="{
					position:'absolute',
					zIndex:'999',
					top: mokaTemplate.ErcodeTop*mokaTemplate.MokaTempRate +'rpx',
					left: mokaTemplate.ErcodeLeft*mokaTemplate.MokaTempRate+'rpx',
					width: mokaTemplate.ErcodeWidth*mokaTemplate.MokaTempRate+'rpx',
					height: mokaTemplate.ErcodeHeight*mokaTemplate.MokaTempRate+'rpx',
					background:'#CCC'
				}" >
				<image :src="UserInfo.WeixinQrcode"  style="width: 100%;height: 100%;"></image>
			</view> -->
			<!-- end：二维码 -->

			<!-- 环绕式顶部文字 由于盒子嵌套问题所有放这 -->
			<view v-if="currentTabIndex === 0 && tweTabIndex === 3" :style="{ 
					position: 'absolute',
					top: mokaTemplate.HeadlineTop*mokaTemplate.MokaTempRate + 'rpx',
					left: mokaTemplate.HeadlineLeft*mokaTemplate.MokaTempRate + 'rpx',
					fontSize: mokaTemplate.HeadlineSize*mokaTemplate.MokaTempRate + 'rpx',
					color: mokaTemplate.HeadlineColor
				 }">
				<text>{{ mokaTemplate.Headline }}</text>
			</view>

			<!-- start：文字标题 -->
			<view class="text-elipasis" :style="{
					position: 'absolute',
					top:mokaTemplate.TitleBoxTop*mokaTemplate.MokaTempRate + 'rpx',
					left:mokaTemplate.TitleBoxLeft*mokaTemplate.MokaTempRate + 'rpx',
					width: mokaTemplate.TextBoxWidth*mokaTemplate.MokaTempRate+'rpx', 
					fontSize: mokaTemplate.TitleSize*mokaTemplate.MokaTempRate+'rpx', 
					color: mokaTemplate.TitleColor,
					zIndex: '999'
				}">
				{{UserInfo.NickName}}
			</view>
			<!-- end：文字标题 -->


			<view :style="{
					width: mokaTemplate.TextBoxWidth*mokaTemplate.MokaTempRate+'rpx', 
					height: mokaTemplate.TextBoxHeight*mokaTemplate.MokaTempRate+'rpx', 
					backgroundColor: mokaTemplate.TextBoxBackgroundColor, 
					top: mokaTemplate.TextBoxTop*mokaTemplate.MokaTempRate + 'rpx', 
					left: mokaTemplate.TextBoxLeft*mokaTemplate.MokaTempRate + 'rpx',
					position: 'absolute',
					zIndex:'99'
				}">
				<view :style="{
						paddingLeft: mokaTemplate.TextBoxPaddingLeft*mokaTemplate.MokaTempRate+'rpx',
						paddingTop: mokaTemplate.TextBoxPaddingTop*mokaTemplate.MokaTempRate+'rpx',
						display:mokaTemplate.TextModelType == 1 ? 'flex' : '',    				// 1 横版 2 竖版
						flexWrap:mokaTemplate.TextModelType == 1 ? 'wrap' : '',    				// 1 横版 2 竖版
					}
				">

					<!-- {{ mokaTemplate.TextModelType }} -->

					<view v-for="(itm,idx) in JSON.parse(mokaTemplate.TextJson).memo" :key="idx" v-if="itm.checked"
						:style="{
							fontSize: mokaTemplate.MemoSize*mokaTemplate.MokaTempRate  + 'rpx',
							color: mokaTemplate.MemoColor, 
							marginBottom:mokaTemplate.TextMarginBottom*mokaTemplate.MokaTempRate+'rpx',
							marginRight:mokaTemplate.TextMarginRight*mokaTemplate.MokaTempRate+'rpx',
						}">
						<view v-if="UserMokaSet.birthShow">
							<view v-if="idx==0"
								:style="{lineHeight:mokaTemplate.TextLineHeight*mokaTemplate.MokaTempRate+'rpx',}">
								<text :style="{
										display:mokaTemplate.TextArrangeType == 2 ? 'block' : ''
									}">
									{{ itm.key }}{{ mokaTemplate.TextEnShow == 1 ? itm.en : ''}}
								</text>
								<text :style="{color: mokaTemplate.TitleColor}">
									{{ itm.value }}
								</text>
							</view>
						</view>
						<view v-if="UserMokaSet.baseShow">
							<view v-if="idx!=0"
								:style="{lineHeight:mokaTemplate.TextLineHeight*mokaTemplate.MokaTempRate+'rpx',}">
								<text :style="{
									display:mokaTemplate.TextArrangeType == 2 ? 'block' : ''
								}">
									{{ itm.key }}{{ mokaTemplate.TextEnShow == 1 ? itm.en : ''}}
								</text>
								<text :style="{color: mokaTemplate.TitleColor}">
									{{ itm.value }}
								</text>
							</view>
						</view>
						<!-- 						<view :style="{lineHeight:mokaTemplate.TextLineHeight*mokaTemplate.MokaTempRate+'rpx',}">
							<text :style="{
									display:mokaTemplate.TextArrangeType == 2 ? 'block' : ''
								}">
								{{ itm.key }}{{ mokaTemplate.TextEnShow == 1 ? itm.en : ''}}
							</text>
							<text :style="{color: mokaTemplate.TitleColor}">
								{{ itm.value }}
							</text>
						</view> -->
					</view>
				</view>
			</view>



			<view
				:style="{position: 'absolute', width: mokaTemplate.PicBoxWidth*mokaTemplate.MokaTempRate+'rpx', height: mokaTemplate.PicBoxHeight*mokaTemplate.MokaTempRate+'rpx', top: mokaTemplate.PicBoxTop*mokaTemplate.MokaTempRate+'rpx', left: mokaTemplate.PicBoxLeft*mokaTemplate.MokaTempRate+'rpx', backgroundColor: mokaTemplate.PicBoxBackgroundColor}">
				<view v-for="(itm, idx) in mokaTemplate.TemplatePics" :key="idx"
					:style="{width: itm.PicWidth*mokaTemplate.MokaTempRate+'rpx', height: itm.PicHeight*mokaTemplate.MokaTempRate+'rpx', position: 'absolute', top: itm.PicTop*mokaTemplate.MokaTempRate+'rpx', left: itm.PicLeft*mokaTemplate.MokaTempRate+'rpx', backgroundColor: '#666'}"
					@touchstart="touchStart($event, idx)" @touchmove="touchMove($event, idx)"
					@touchend="touchEnd($event)" :id="'images' + idx"
					:class="imageIndex[0].index == idx && isIndex ? 'image-active' :''">
					<view v-if="showChangPicBtn == idx" class="tihuanBtn" @click="changPic(idx)">替换</view>
					<movable-area scale-area style="width:100%;height:100%; overflow: hidden;">
						<movable-view scale :x="0" :y="0" direction="all" @change="onChange($event, idx)"
							@scale="onScale($event, idx)"
							:style="{width:'100%', height: mokaTemplate.TemplatePics[idx].imgheight + 'rpx'}">
							<image :src="itm.PicSrc" mode="widthFix" @load="imageLoad($event, idx)"
								:style="{width:'100%', display: 'block'}" @click="changPicBtn(idx)">
						</movable-view>
					</movable-area>
					<!--  -->
				</view>
			</view>
		</view>

		<view class="actBottom flexbc">
			<view style="width:180rpx;" class="flexbc">
				<fui-icon name="arrowleft" color="#999" size="30" @click="goBack"></fui-icon>
				<!-- <view style="height:35rpx;line-height:35rpx;font-size:12rpx;">拖拽挪动 单击换图</view> -->
			</view>
			<!-- <view style="width:300rpx;padding:8rpx;margin-left:20rpx;">
				<fui-slider color="#FF3300" @change="onChange" @changing="onChanging"></fui-slider>
			</view> -->
			<view style="width:300rpx;" class="flexbc">
				<button @click="showDrawer" class="editBtn">编辑</button>
				<button @click="saveMoka" class="makeBtn">生成模卡</button>
			</view>
		</view>
		<!-- <image :src="textImage1" style="width: 500rpx;height: 500rpx;"></image>
		<image :src="textImage2" style="width: 500rpx;height: 500rpx;"></image> -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
				textImage1: "",
				textImage2: "",
				showLoading: false,
				// drawerShow: false,
				showRight: false,
				showLeft: false,
				itemList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
				TargetUserID: 0,
				mokaTemplateID: 0,
				mokaTemplate: {},
				// mokaTempRate: 0.8,
				tempFiles: [],
				mokaImages: [],
				mokaImageLocal: [],
				UserMokaSet: {
					backgroundColor: true,
					birthShow: true,
					baseShow: true,
					erCodeShow: true
				},
				UserInfo: [],
				showChangPic: false,
				showChangPicBtn: -1,
				// 一级tab值
				currentTabIndex: 0,
				// 二级tab值
				tweTabIndex: 0,



				// 滑动切换照片数据
				isIndex: false,
				topLeft: [],
				imageIndex: null,
				elementOneIndex: null,


				movableList: []
			};
		},
		onLoad(option) {
			let tabData = uni.getStorageSync("tabData")
			this.tweTabIndex = tabData.tweLevelTabIndex;
			this.currentTabIndex = tabData.currentTabIndex;
			this.mokaTemplateID = option.mokaTemplateID
			this.TargetUserID = option.otherID
			this.tempFiles = uni.getStorageSync("tempMoka");


			this.onGetMokaTemplate();

		},
		onShow() {
			this.showLoading = false;
		},
		watch: {
			'mokaTemplate.TemplatePics': {
				handler: function(newVal, oldVal) {
					this.mokaTemplate.TemplatePics = newVal;
				},
				deep: true,
				immediate: true
			}
		},
		mounted() {
			wx.setPageOrientation({
				orientation: 'landscape'
			});
		},
		methods: {
			touchStart(event, index) {
				this.isMove = false;
				// 接收第一张照片 index
				this.elementOneIndex = index;

				// 第一张照片关闭边框
				this.isIndex = false;

			},
			touchMove(event) {

				// 鼠标移动的x，y坐标
				var clientX = event.changedTouches[0].clientX;
				var clientY = event.changedTouches[0].clientY;

				var top = this.topLeft[this.elementOneIndex].top
				var bottom = this.topLeft[this.elementOneIndex].bottom
				var left = this.topLeft[this.elementOneIndex].left
				var right = this.topLeft[this.elementOneIndex].right

				if (clientX <= left || clientY <= top || clientX >= right || clientY >= bottom) this.isMove = true;

				if (!this.isMove) return;

				// console.log('clientX', clientX)
				// console.log('clientY', clientY)
				// 筛选符合条件图片的 index
				this.imageIndex = this.topLeft.filter((item, index) => clientX >= item.left && clientY >= item.top &&
					clientX <= item.right && clientY <= item.bottom)
				// console.log('this.imageIndex', this.imageIndex)
				// return;
				// 添加边框
				if (this.elementOneIndex == this.imageIndex[0].index) {
					this.isIndex = false;
				} else {
					this.isIndex = true;
				}

			},
			touchEnd(event) {
				if (!this.isMove) return;
				var ObjPicSrc = this.tempFiles[this.elementOneIndex].tempFilePath;
				this.tempFiles[this.elementOneIndex].tempFilePath = this.tempFiles[this.imageIndex[0].index].tempFilePath;
				this.tempFiles[this.imageIndex[0].index].tempFilePath = ObjPicSrc;
				uni.setStorageSync("tempMoka", this.tempFiles);

				this.tempFiles.forEach((item, index) => {
					this.mokaTemplate.TemplatePics[index]['PicSrc'] = item.tempFilePath;
				})
				// this.mokaTemplate.TemplatePics[index]['PicSrc'] = this.tempFiles[index].tempFilePath

				this.isIndex = false;
				this.mokaTemplate.TemplatePics[this.elementOneIndex].local.x = 0;
				this.mokaTemplate.TemplatePics[this.elementOneIndex].local.y = 0;
				this.mokaTemplate.TemplatePics[this.imageIndex[0].index].local.x = 0;
				this.mokaTemplate.TemplatePics[this.imageIndex[0].index].local.y = 0;

				// this.textImage1 = this.mokaTemplate.TemplatePics[1].PicSrc;
				// this.textImage2 = this.mokaTemplate.TemplatePics[2].PicSrc;
				// this.mokaTemplate.TemplatePics[index]['PicSrc'] = this.tempFiles[index].tempFilePath;
			},

			goBack() {
				uni.navigateBack()
			},
			birthChange(e) {
				this.UserMokaSet.birthShow = e.detail.value
				// console.log(this.UserMokaSet.birthShow)
			},
			baseChange(e) {

				this.UserMokaSet.baseShow = e.detail.value
			},
			erCodeChange(e) {

				this.UserMokaSet.erCodeShow = e.detail.value
			},
			bgcolorChange(e) {
				;

				if (this.mokaTemplate.BackgroundColor == '#FFFFFF') {
					this.mokaTemplate.BackgroundColor = '#000000'
					this.UserMokaSet.backgroundColor = !this.UserMokaSet.backgroundColor
					this.mokaTemplate.TitleColor = '#FFFFFF'
				} else if (this.mokaTemplate.BackgroundColor == '#000000') {
					this.mokaTemplate.BackgroundColor = '#FFFFFF'
					this.UserMokaSet.backgroundColor = !this.UserMokaSet.backgroundColor
					this.mokaTemplate.TitleColor = '#000000'
				}

				// console.log('bgcolorChange', this.mokaTemplate.BackgroundColor);
				// console.log('TitleColor', this.mokaTemplate.TitleColor);
			},
			//调用此方法显示抽屉
			showDrawer(type) {
				this.$refs.showRight.open();
				// this.drawerShow = true
			},
			closeDrawer(type) {
				this.$refs.showRight.close();
				// this.drawerShow = false
			},
			onGetMokaTemplate() {

				this.$httpost('/Moka/Template', {
					TemplateID: this.mokaTemplateID,
					OtherID: this.TargetUserID
				}).then(res => {
					// console.log('Template', res);

					if (res.code == 200) {
						this.mokaTemplate = res.data.MokaTemplate;
						this.UserInfo = res.data.MokaUserInfo;
						this.mokaTemplate.TemplatePics.forEach((val, index) => {
							this.mokaTemplate.TemplatePics[index]['PicSrc'] = this.tempFiles[index]
								.tempFilePath;
							this.mokaTemplate.TemplatePics[index]['local'] = {
								source: "touch",
								x: 0,
								y: 0
							};
							if (this.mokaTemplate.TemplatePics.length - 1 == index) {
								setTimeout(() => {
									this.mokaTemplate.TemplatePics.forEach((item, index) => {
										var query = uni.createSelectorQuery().in(this);
										query.select(`#images${index}`).boundingClientRect(
											data => {
												// return;
												this.topLeft.push({
													top: data.top,
													left: data.left,
													bottom: data.bottom,
													right: data.right,
													index
												})
												// console.log('元素获取', data)
											}).exec();
									})
								}, 1000)
							}
						});

						// console.log(this.mokaTemplate);
					}

				});
			},
			ontestChange(e) {
				console.log(e)
			},
			changPicBtn(index) {
				this.showChangPic = !this.showChangPic
				if (this.showChangPic == true) {
					this.showChangPicBtn = index;
				} else {
					this.showChangPicBtn = -1;
				}
			},
			changPic(index) {
				let _that = this;
				uni.chooseMedia({
					count: 1,
					mediaType: ['image'],
					sourceType: ['album'],
					success(res) {
						// console.log(res)
						_that.setPics(index, res.tempFiles)
					}
				})
			},
			setPics(index, tempFiles) {
				this.tempFiles.splice(index, 1, tempFiles[0]);
				uni.setStorageSync("tempMoka", this.tempFiles);

				this.mokaTemplate.TemplatePics[index]['PicSrc'] = this.tempFiles[index].tempFilePath;
			},
			imageLoad(e, index) {
				// console.log('image DOM', e)
				// 当图片加载完成后，获取图片的原始宽度和高度，并根据宽度计算出高度
				const {
					width,
					height
				} = e.detail;
				const initW = this.mokaTemplate.TemplatePics[index]['PicWidth'] * this.mokaTemplate.MokaTempRate;
				const initH = this.mokaTemplate.TemplatePics[index]['PicHeight'] * this.mokaTemplate.MokaTempRate;
				// console.log('initW', initW)

				// console.log()
				// 高度 = 原始高度 / 原始宽度 * initW
				this.mokaTemplate.TemplatePics[index]['imgheight'] = (height / width) * initW;
				// console.log('mokaTemplate.TemplatePics', this.mokaTemplate.TemplatePics)
			},
			// 触发缩放
			onScale(e, index) {

				console.log('event1', e.detail)

				// console.log('index1', index)

				this.mokaTemplate.TemplatePics[index]['scale'] = e.detail
			},
			// 触发拖动移动
			onChange(e, idx) {
				console.log('event2', e.detail)
				// this.movableList
				this.mokaTemplate.TemplatePics[idx]['local'] = e.detail;

				// console.log('mokaTemplatexxxxxxxxxxx', this.mokaTemplate);
			},
			saveMoka() {
				// console.log('this.mokaTemplate.TemplatePics', this.mokaTemplate.TemplatePics)
				// this.textImage1 = this.mokaTemplate.TemplatePics[1].PicSrc;
				// this.textImage2 = this.mokaTemplate.TemplatePics[2].PicSrc;
				// return;
				this.mokaImages = [];
				this.mokaImageLocal = [];

				this.showLoading = true;
				// console.log('UserMokaSet', this.UserMokaSet);

				this.$httpost('/Moka/SaveMoka', {
					templateID: this.mokaTemplateID,
					TargetUserID: this.TargetUserID,
					UserMokaSet: this.UserMokaSet
				}).then(async res => {

					let a = -1;
					let b = -1;
					let c = a - b - b;
					console.log('SaveMoka', c);


					if (res.code == 200) {

						let UserMokaID = res.data;

						const tempFilePaths = this.tempFiles;
						console.log('tempFilePaths', tempFilePaths);

						for (var i = 0; i < tempFilePaths.length; i++) {

							this.mokaTemplate.TemplatePics[i]['local']['scale'] = this.mokaTemplate
								.TemplatePics[i]['scale']

							this.mokaImageLocal.push(this.mokaTemplate.TemplatePics[i]['local']);
							// console.log('报错信息', this.mokaTemplate.TemplatePics[i]['local'])

							try {
								let ResData = await this.uploadImage(tempFilePaths, i)
								this.mokaImages.push(this.$baseUrl + ResData.fileName);

							} catch (err) {
								this.showLoading = false;
								// console.log('上传失败', err)
							}
						}



						if (this.mokaImages.length == tempFilePaths.length) {

							this.$httpost('/Moka/MakeMoka', {
								UserMokaID: UserMokaID,
								MokaImages: this.mokaImages,
								MokaImageLocal: this.mokaImageLocal
							}).then(MakeMokaRes => {

								// console.log('MakeMokaRes', MakeMokaRes)
								if (MakeMokaRes.code == 200) {
									uni.navigateTo({
										url: '/moka/pages/mokaResult?mokaid=' + MakeMokaRes
											.data.MokaID
									})
								}
							}).catch(err => {
								this.showLoading = false;
								uni.showToast({
									title: '上传失败！',
									icon: 'errr'
								})
								// console.log(err)
							})
						}

					}

				}).catch(err => {
					this.showLoading = false;
					// console.log(err)
				})
			},
			uploadImage(tempFilePaths, i) {
				return new Promise((reslove, reject) => {
					uni.uploadFile({
						url: this.$imgUpload + 'Moka&type=image',
						filePath: tempFilePaths[i].tempFilePath,
						name: "file",
						// files: tempFilePaths,
						formData: {},
						success: (uploadFileRes) => {
							// console.log('uploadFileRes', uploadFileRes);
							reslove(JSON.parse(uploadFileRes.data))
							// let ResData = ;
							// console.log('mokaImages', this.mokaImages)
							// console.log(this.mokaImages.length, tempFilePaths.length)
						},
						fail: (err) => {
							reject(err)
						}
					});
				})
			},
		}
	}
</script>

<style lang="scss">
	.switch-box {
		padding-left: 30rpx;
		padding-right: 30rpx;
	}

	.switch-title {
		font-size: 12rpx;
		color: #FFF;
		line-height: 40rpx;
	}

	.text-elipasis {
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
		text-overflow: ellipsis;
		line-height: 1.2;
	}

	.surround {
		text-align: center;
	}

	/* 自定义内容区样式需自行控制 */
	.fui-scroll__view {
		width: 520rpx;
		flex: 1;
		overflow: hidden;
	}

	.actBottom {
		position: fixed;
		z-index: 500;
		bottom: 0rpx;
		width: calc(100% - 20rpx);
		background-color: #000;
		padding: 10rpx;
	}

	.editBtn {
		height: 30rpx;
		line-height: 30rpx;
		font-size: 12rpx;
		width: 80rpx;
		border: 1rpx solid $globalColor;
		background: none;
		color: #FFF
	}

	.makeBtn {
		height: 30rpx;
		line-height: 30rpx;
		font-size: 12rpx;
		width: 80rpx;
		background-color: $globalColor;
	}

	.tihuanBtn {
		position: absolute;
		z-index: 500;
		left: 50%;
		margin-left: -20rpx;
		top: 50%;
		margin-top: -20rpx;
		width: 40rpx;
		height: 40rpx;
		background: #FFDD00;
		border: 3rpx solid rgba(0, 0, 0, 0.5);
		border-radius: 40rpx;
		color: #000;
		text-align: center;
		font-size: 12rpx;
		line-height: 40rpx;
	}

	.drawerBox * {
		font-size: 12rpx;
	}

	.image-active {
		border: 2rpx solid #ffeb0b;
		box-sizing: border-box;
	}
</style>